import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    // 用户信息
    userInfo: JSON.parse(localStorage.getItem('userInfo') || '{}'),
    // 是否已登录
    isLogin: !!localStorage.getItem('token'),
    // 展览列表
    exhibitions: [],
    // 解说员列表
    guides: [],
    // 公告列表
    announcements: []
  },
  mutations: {
    // 设置用户信息
    SET_USER_INFO(state, userInfo) {
      state.userInfo = userInfo
      localStorage.setItem('userInfo', JSON.stringify(userInfo))
    },
    // 设置登录状态
    SET_LOGIN_STATE(state, isLogin) {
      state.isLogin = isLogin
    },
    // 设置token
    SET_TOKEN(state, token) {
      localStorage.setItem('token', token)
    },
    // 清除用户信息
    CLEAR_USER_INFO(state) {
      state.userInfo = {}
      state.isLogin = false
      localStorage.removeItem('userInfo')
      localStorage.removeItem('token')
    },
    // 设置展览列表
    SET_EXHIBITIONS(state, exhibitions) {
      state.exhibitions = exhibitions
    },
    // 设置解说员列表
    SET_GUIDES(state, guides) {
      state.guides = guides
    },
    // 设置公告列表
    SET_ANNOUNCEMENTS(state, announcements) {
      state.announcements = announcements
    }
  },
  actions: {
    // 登录
    login({ commit }, { token, userInfo }) {
      commit('SET_TOKEN', token)
      commit('SET_USER_INFO', userInfo)
      commit('SET_LOGIN_STATE', true)
    },
    // 登出
    logout({ commit }) {
      commit('CLEAR_USER_INFO')
    },
    // 获取展览列表
    async getExhibitions({ commit }) {
      try {
        const { data } = await Vue.prototype.$http.get('/exhibition/list')
        commit('SET_EXHIBITIONS', data.data.records)
        return data.data.records
      } catch (error) {
        console.error('获取展览列表失败', error)
        return []
      }
    },
    // 获取解说员列表
    async getGuides({ commit }) {
      try {
        const { data } = await Vue.prototype.$http.get('/guide/list')
        commit('SET_GUIDES', data.data)
        return data.data
      } catch (error) {
        console.error('获取解说员列表失败', error)
        return []
      }
    },
    // 获取公告列表
    async getAnnouncements({ commit }) {
      try {
        const { data } = await Vue.prototype.$http.get('/announcement/list')
        commit('SET_ANNOUNCEMENTS', data.data.records)
        return data.data.records
      } catch (error) {
        console.error('获取公告列表失败', error)
        return []
      }
    }
  },
  getters: {
    // 获取用户信息
    userInfo: state => state.userInfo,
    // 获取登录状态
    isLogin: state => state.isLogin,
    // 获取用户角色
    userRole: state => state.userInfo.role || '',
    // 判断是否是管理员
    isAdmin: state => state.userInfo.role === 'ADMIN',
    // 获取展览列表
    exhibitions: state => state.exhibitions,
    // 获取解说员列表
    guides: state => state.guides,
    // 获取公告列表
    announcements: state => state.announcements
  }
})